package top.kpromise.user.service_imp;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.sentry.Sentry;
import org.springframework.stereotype.Service;
import top.kpromise.user.data.Config;
import top.kpromise.user.service.SmsService;
import top.kpromise.user.utils.RegularUtils;

import java.util.HashMap;

@Service
public class SmsServiceImp implements SmsService {

    @Override
    public boolean createUserCode(String phone, String code) {
        return sendSms(phone, code, Config.TemplateCode.createUser);
    }

    @Override
    public boolean findPasswordCode(String phone, String code) {
        return false;
    }

    @Override
    public boolean loginCode(String phone, String code) {
        return false;
    }

    private IAcsClient iAcsClient;

    private IAcsClient initClient() {
        DefaultProfile profile = DefaultProfile.getProfile(Config.AliYunAccount.regionId, Config.AliYunAccount.accessKeyId,
                Config.AliYunAccount.secret);
        return new DefaultAcsClient(profile);
    }

    private boolean sendSms(String phone, String code, String templateCode) {
        return sendSms(phone, code, templateCode, Config.AliYunAccount.defaultSignName);
    }

    private boolean sendSms(String phone, String code, String templateCode, String signName) {
        IAcsClient client = iAcsClient;
        if (client == null) {
            client = initClient();
            iAcsClient = client;
        }
        if (signName == null) {
            signName = Config.AliYunAccount.defaultSignName;
        }

        CommonRequest request = new CommonRequest();
        request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", RegularUtils.phoneNumberWithoutCountryCode(phone));
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            HashMap<String, String> map = new HashMap<>();
            map.put("code", code);
            request.putQueryParameter("TemplateParam", objectMapper.writeValueAsString(map));
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return true;
        } catch (Exception e) {
            Sentry.capture(e);
            e.printStackTrace();
            return false;
        }
    }
}
